Page({
  data: {
    payment: false,
    hasCoupon: false,
    isFullMail: false,
    isUsePoints: true,
    needUsePoints: true,
    insufficient: false,
    isNeedInvoice: false,   // 下单时判断是否开票
    allowlogistics: false,  // 是否允许选择物流
    allowSelfPickup: false, // 是否允许到店自提
    selectedInvoice: false, // 是否开票的状态展示
    selectedDelivery: -1,   // 默认选择快递配送
    needDelivery: -1,
    selectedExpress: -1,
    needExpress: -1,
    selectedPickupPoint: -1,
    needPickupPoint: -1,
    couponMoney: 0,
    invoiceIdx: 0,
    selectedPoints: 0,
    pointsMoney: 0,
    tax: 0,
    remark: '',
    delivery: [
      {id: 1, name: '快递'},
      {id: 2, name: '自提'},
      {id: 3, name: '本地'},
      {id: 4, name: '门店配送'},
      {id: 5, name: '虚拟商品'},
      {id: 6, name: '货到付款'}
    ],
  },
  onLoad: function (options) {
    this.setData({
      type: options.type,
      data: options.data
    });
  },
  onShow: function () {
    if (wx.user.hasLogin()) {
      this.getOrderInfo();
      this.getInvoiceInfo();
    }
  },
  getOrderInfo: function () {
    wx.util.request('order.preview', {
      body: {
        type: this.data.type,
        data: this.data.data
      }
    }).then(res => {
      let totalWeight = 0,
          productList = res.products,
          coupons = res.coupons,
          isFullMail = res.is_full_mail,
          productMoney = Number(res.preview.product_money), //Math.round(res.preview.product_money * 100) / 100,
          freight = isFullMail ? 0 : Number(res.preview.shipping_money),
          pickupConfig = res.pickup_point_config,
          maxUsePoints = res.max_use_point,
          canUsePointsPay = false;
      for (let item of productList) {
        // 判断所有商品是否都能使用积分支付
        if (item.point_exchange_type == 3) {
          canUsePointsPay = true;
        } else {
          canUsePointsPay = false;
          break;
        }
        // 计算商品总重
        totalWeight += item.weight * item.num;
      }
      for (let item of coupons) {
        item.start_time = wx.time.toDate(item.start_time, 'Y-M-D');
        item.end_time = wx.time.toDate(item.end_time, 'Y-M-D');
      }
      // 筛选可用优惠券
      coupons = coupons.filter(entity => {
        // 目前暂不支持限定商品的优惠券
        if (!entity.couponProduct || entity.couponProduct.length == 0) {
          // 需要达到满减规则
          return entity.at_least <= productMoney;
        }
      });
      if (this.data.selectedCouponIdx) {
        coupons[this.data.selectedCouponIdx].checked = true;
      }
      let preview = {
        account: res.account,
        address: res.address,
        productList: productList,
        company: res.company,
        marketing: res.marketing_details,
        coupons: coupons,
        hasCoupon: (coupons.length > 0),
        canUseCouponNum: coupons.length,
        invoice: res.invoice,
        pointConfig: res.point_config,
        pickupConfig: pickupConfig,
        proOrimoney: Number(res.preview.product_original_money).toFixed(2),
        productMoney: productMoney.toFixed(2),
        totalWeight: totalWeight,
        isFullMail: isFullMail,
        isLogistics: res.is_logistics,
        freight: freight.toFixed(2),
        showFreight: freight.toFixed(2),
        shippingMoney: freight.toFixed(2),  // 预留项：运费
        actualAmount: wx.util.formatAmount(productMoney + freight),
        canUsePointsPay: canUsePointsPay,
        allowlogistics: (res.is_logistics == '1'),
        allowSelfPickup: (pickupConfig.buyer_self_lifting == '1'),
      };
      // 是否开启积分抵扣
      if (preview.pointConfig.is_open == '1' && maxUsePoints > 0) {
        preview.userPoints = preview.account.user_integral;
        preview.isEnablePoints = true;
        preview.pointsMax = preview.userPoints >= maxUsePoints ? maxUsePoints : preview.userPoints;
        preview.pointsMoneyMax = preview.pointsMax * preview.pointConfig.convert_rate;
        preview.selectedPoints = preview.pointsMax;
        preview.pointsMoney = preview.pointsMoneyMax;
      }
      this.setData(preview);
      this.calcActualAmount();
    }).catch(err => {
      console.log(err);
    });
  },
  getInvoiceInfo: function () {
    wx.util.request('invoice.default').then(res => {
      this.setData({
        myInvoice: res
      });
    });
  },
  inputRemark: function (e) {
    this.setData({
      remark: e.detail.value
    });
  },
  chooseAddr: function () {
    wx.navigateTo({
      url: "../address/index?goBack=1"
    });
  },
  showPopup: function (e) {
    this.setData({
      popupShow: true,
      popupType: e.currentTarget.dataset.type
    });
  },
  changeSelected: function (e) {
    let name = e.currentTarget.dataset.name,
        value = e.currentTarget.dataset.value,
        data = {};
    switch (name) {
      case 'deliveryType':
        data.selectedDelivery = value;
        data.showFreight = this.data.shippingMoney;
        break;
      case 'express':
        data.selectedExpress = value;
        if (this.data.address) {
          this.queryFreight(this.data.company[value].id);
        }
        break;
      case 'pickupPoint':
        data.selectedPickupPoint = value;
        break;
      case 'openInvoice':
        data.selectedInvoice = (value != 0);
        break;
      case 'invoiceContent':
        data.invoiceIdx = value;
        break;
    }
    this.setData(data);
  },
  selectInvoice: function () {
    wx.navigateTo({
      url: "../invoice/index?goBack=1"
    });
  },
  chooseCoupon: function (e) {
    let idxArr = e.detail.value,
        idx = idxArr[idxArr.length - 1] || -1,
        coupons = this.data.coupons;
    for (let i in coupons) {
      coupons[i].checked = false;
      if (i == idx) {
        coupons[i].checked = true;
      }
    }
    this.setData({
      tempCouponIdx: idx,
      coupons: coupons
    });
  },
  pointsUseState: function () {
    this.setData({
      isUsePoints: !this.data.isUsePoints
    });
    this.calcActualAmount();
  },
  inputPoints: function (e) {
    this.setData({
      selectedPoints: e.detail.value
    });
  },
  select: function () {
    let d = this.data,
        popupType = d.popupType,
        data = {},
        couponMoney = 0;
    switch (popupType) {
      case 'logistics':
        let selectedDelivery = d.selectedDelivery;
        data.needDelivery = selectedDelivery;
        switch (selectedDelivery) {
          case -1:
            wx.util.toast('请选择配送方式');
            return;
            break;
          case 0:
            data.logisticsTitle = '商家指定快递';
            data.freight = this.data.shippingMoney;
            // 兼容不可指定快递公司的情况
            if (d.company.length > 0) {
              if (d.selectedExpress < 0) {
                wx.util.toast('请选择快递公司');
                return;
              }
              data.needExpress = d.selectedExpress;
              data.logisticsTitle = d.company[d.selectedExpress].title;
              data.freight = d.showFreight;
            }
            break;
          case 1:
            if (d.selectedPickupPoint < 0) {
              wx.util.toast('请选择自提点');
              return;
            }
            data.needPickupPoint = d.selectedPickupPoint;
            data.logisticsTitle = d.pickupConfig.list[d.selectedPickupPoint].name;
            // 自提满额可减免费用
            data.freight = d.productMoney >= Number(d.pickupConfig.pickup_point_freight) ? 0 : Number(d.pickupConfig.pickup_point_fee).toFixed(2);
            break;
          default:
            data.logisticsTitle = d.delivery[selectedDelivery].name;
            data.showFreight = 0;
            data.freight = 0;
            break;
        }
        break;
      case 'invoice':
        if (!d.myInvoice) {
          wx.util.toast('请点击“个人”或“单位”选择开票信息');
          return;
        }
        data.invoiceTitle = d.myInvoice.title;
        data.isNeedInvoice = d.selectedInvoice;
        break;
      case 'coupon':
        let name = null,
            idx = d.tempCouponIdx;
        if (idx > -1) {
          let coupon = d.coupons[idx];
          name = coupon.title;
          if (coupon.type == 1) {
            // 满减
            couponMoney = coupon.money;
          } else if (coupon.type == 2) {
            // 折扣
            couponMoney = d.productMoney * (1 - coupon.discount / 100);
          }
        }
        data.selectedCouponIdx = idx;
        data.selectedCouponName = name;
        data.couponMoney = couponMoney.toFixed(2);
        break;
      case 'points':
        data.needUsePoints = d.isUsePoints;
        data.usePoints = d.isUsePoints ? d.selectedPoints : 0;
        data.pointsMoney = d.isUsePoints ? d.selectedPoints * d.pointConfig.convert_rate : 0;
        break;
    }
    this.setData(data, () => {
      this.calcActualAmount();
    });
    this.hidePopup();
  },
  queryFreight: function (expressId) {
    if (this.data.isFullMail || !expressId) {
      return;
    }
    wx.util.request('order.freight', {
      body: {
        type: this.data.type,
        data: this.data.data,
        address_id: this.data.address.id,
        company_id: expressId
      }
    }).then(res => {
      this.setData({
        showFreight: Number(res.shipping_money).toFixed(2)
      });
    });
  },
  hidePopup: function () {
    let rawData = this.data,
        popupType = rawData.popupType,
        newData = {popupShow: false};
    switch (popupType) {
      case 'logistics':
        // 判断是否将未提交的配送方式还原
        if (rawData.needDelivery != rawData.selectedDelivery) {
          newData.selectedDelivery = rawData.needDelivery;
        }
        // 判断是否将未提交的快递选择状态还原
        if (rawData.selectedDelivery == 0 && rawData.needExpress != rawData.selectedExpress) {
          newData.selectedExpress = rawData.needExpress;
          newData.showFreight = rawData.freight;
        }
        // 判断是否将未提交的自提门店选择还原
        if (rawData.selectedDelivery == 1 && rawData.needPickupPoint != rawData.selectedPickupPoint) {
          newData.selectedPickupPoint = rawData.needPickupPoint;
        }
        break;
      case 'invoice':
        // 判断是否将未提交的开票需求状态还原
        if (rawData.isNeedInvoice != rawData.selectedInvoice) {
          newData.selectedInvoice = rawData.isNeedInvoice;
        }
        break;
      case 'coupon':
        // 判断是否将未提交的卡券变更还原
        let tempIdx = rawData.tempCouponIdx,
            selectedIdx = rawData.selectedCouponIdx;
        if (tempIdx != selectedIdx) {
          if (tempIdx > -1) {
            newData[`coupons[${tempIdx}].checked`] = !rawData.coupons[tempIdx].checked;
          }
          if (selectedIdx) {
            newData[`coupons[${selectedIdx}].checked`] = !rawData.coupons[selectedIdx].checked;
          }
        }
        break;
      case 'points':
        // 判断是否将未提交的积分变更还原
        if (rawData.usePoints != rawData.selectedPoints) {
          newData.isUsePoints = rawData.needUsePoints;
          // newData.pointsMoney = rawData.pointsMoney || rawData.pointsMoneyMax;
          // newData.selectedPoints = rawData.usePoints || rawData.pointsMax;
        }
        break;
    }
    this.setData(newData);
  },
  calcActualAmount: function () {
    // 发票税费计算规则：税率 * (订单总金额 - 积分抵现 - 优惠券)
    // 实付金额计算规则：运费 + (1 + 税率) * (订单总金额 - 积分抵现 - 优惠券)
    let freight = (this.data.needDelivery > 1 ? 0 : parseFloat(this.data.freight)),
        orderMoney = this.data.productMoney - this.data.pointsMoney - this.data.couponMoney, // 商品实付金额
        taxRate = (this.data.isNeedInvoice ? this.data.invoice.order_invoice_tax : 0) / 100, // 税率
        tax = taxRate * orderMoney,                                                          // 税费
        actualAmount = freight + orderMoney + tax;                                           // 订单实付金额
    this.setData({
      tax: tax.toFixed(2),
      actualAmount: wx.util.formatAmount(actualAmount)
    });
  },
  btnPay: function () {
    let data = this.data,
        deliveryIdx = data.selectedDelivery;
    // 物流信息检查
    if (data.isLogistics && deliveryIdx < 0) {
      this.setData({
        modal: true,
        modalContent: '请选择配送方式'
      });
      return;
    }
    if (deliveryIdx != 1 && deliveryIdx != 4 && !this.data.address) {
      if (!data.address) {
        this.setData({
          modal: true,
          modalContent: '请先设置您的收货地址'
        });
        return;
      }
      // 快递、自提二选一
      /*if (deliveryIdx == 0 && data.needExpress > -1) {
        postData.company_id = data.company[data.needExpress].id;
      } else if (deliveryIdx == 1 && data.needPickupPoint > -1) {
        postData.pickup_id = data.pickupConfig.list[data.needPickupPoint].id;
      }*/
    }
    this.setData({
      payment: true
    }, () => {
      wx.showLoading();
      // 下单
      wx.util.request('order.new', {
        body: {
          type: data.type,
          data: data.data,
          shipping_type: deliveryIdx > -1 ? data.delivery[deliveryIdx].id : 1,
          address_id: (data.address && data.address.id) || 0, 
          company_id: data.needExpress > -1 ? data.company[data.needExpress].id : 0,
          coupon_id: data.selectedCouponIdx > -1 ? data.coupons[data.selectedCouponIdx].id : 0,
          pickup_id: data.needPickupPoint > -1 ? data.pickupConfig.list[data.needPickupPoint].id : 0,
          use_point: data.isUsePoints ? data.selectedPoints : 0,
          invoice_id: data.isNeedInvoice && data.myInvoice ? data.myInvoice.id : 0,
          invoice_content: data.invoice.list[data.invoiceIdx] || '',
          distribution_time_out: '',
          buyer_message: data.remark,
        }
      }).then(res => {
        // 选择支付渠道
        let page = (res.pay_status == 1 ? 'result' : 'index');
        // 跳转支付结果页
        wx.redirectTo({
          url: `../payment/${page}?id=${res.id}`
        });
      });
      setTimeout(() => {
        this.setData({
          payment: false
        });
      }, 2000);
    });
  },
  hideModal: function () {
    this.setData({
      modal: false
    });
  },
})